import {getPreferenceValues} from "@raycast/api";
import axios from "axios";
import jwt from "jwt-simple";
import EventSource from "eventsource"

export const generateToken = () => {
    const {apikey, apisecret} = getPreferenceValues()

    console.log("apikey",apikey)
    console.log("apisecret",apisecret)

    const payload = {
        "api_key": apikey,
        "exp": Date.now().valueOf() + 100000,
        "timestamp": Date.now().valueOf(),
    }

    return jwt.encode(payload, apisecret, 'HS256',{header:{"alg": "HS256", "sign_type": "SIGN"}})
}


interface requestOption {
    model: 'chatglm_pro' | 'chatglm_std' | 'chatglm_lite'
    req: requestReq
}


/**
 * 请求参数 [参考地址](https://open.bigmodel.cn/dev/api#chatglm_pro)
 */
interface requestReq {
    prompt: {
        /**
         * 本条信息作者的角色，可选择user 或 assistant
         * - user 指用户角色输入的信息
         * - assistant 指模型返回的信息
         */
        role: 'user' | 'assistant',
        /**
         * 本条信息的具体内容
         */
        content: string }[]
}

/**
 * 返回参数
 */
interface requestResp {
    code: number,
    msg: string,
    data: {
        request_id: '7898786015217616656',
        task_id: '7898786015217616656',
        task_status: 'SUCCESS',
        choices: {role:string,content:string}[],
    },
    success: true

}

export const request = (opt: requestOption) => {
    const token = generateToken()
    return axios<requestResp>({
        url: `https://open.bigmodel.cn/api/paas/v3/model-api/${opt.model}/invoke`,
        method: "POST",
        data:JSON.stringify(opt.req),
        headers: {
            "Authorization": token,
            "Content-Type":"application/json"
            // "accept": "text/event-stream"
        }
    })
}